﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace AMS.WebDL.Php.Models
{
    class RangedPhpDownloaderModel
    {
        public void DownloadRange(string pageDirectory, string pageText, string elementText, int first, int last, DirectoryInfo localDirectory)
        {
            // Validate address format (http, .php, etc)
            ValidatePageText(pageText);
            ValidateAddress(pageDirectory);
            
            for (int i = first; i <= last; i++)
            {
                // form temporary address
                string remoteFileName = pageText + '?' + elementText + '=' + i.ToString()
                string address = pageDirectory + remoteFileName;

                string localFileName = String.Format("{0}_{1}_{2}.html", pageText.Substring(0, pageText.Length-4), elementText, i.ToString());
                localFileName = Path.Combine(localDirectory.FullName, localFileName);
                int j = 0;
                while (!File.Exists(localFileName))
                {
                    j++;
                    localFileName = String.Format("{0}_{1}_{2}({3}).html", pageText.Substring(0, pageText.Length-4), elementText, i.ToString(), j.ToString());
                    localFileName = Path.Combine(localDirectory.FullName, localFileName);
                }

                DownloadFile(address, localFileName);                
                DownloadCssJs(pageDirectory, new FileInfo(localFileName));
            }
        }

        private void ValidatePageText(string pageText)
        {
            throw new NotImplementedException();
            // ends with .php
            // spaces replaced with %20
            // no illegal characters
        }

        private void ValidateAddress(string baseAddress)
        {
            throw new NotImplementedException();
            // starts with http://
            // ends with /
            // spaces replaced  with %20
            // no illegal characters
        }

        private void DownloadFile(string webPageAddress, string localFilename)
        {
            WebClient client = new WebClient();
            client.DownloadFile(webPageAddress, localFilename);
        }

        private void DownloadCssJs(string pageDirectory, FileInfo localFile)
        {
            throw new NotImplementedException();
            // download CSS (overwrite?)
            //   watch for subdirectories!
            // download JS (overwrite?)
            //   watch for subdirectories!
        }
    }
}
